﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Windows.Forms;
using ScreenSharing.sdk;
using SmartConference.SmartPlayer;

namespace ScreenSharing.smartTool
{
    public partial class PlayForm : Form
    {
        private PlayerManager _playerManager { get; set; }
        private string _url { get; }

        public PlayForm(string url)
        {
            _url = $"{ConfigurationManager.AppSettings["RtmpServer"]}/{url}";
            InitializeComponent();
           this.WindowState = FormWindowState.Maximized;
           this.FormBorderStyle = FormBorderStyle.None;
            this.Load += PlayForm_Load;
            this.Closing += PlayForm_Closing;
        }

        private void PlayForm_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                _playerManager?.Close();
            }
            catch (Exception ex)
            {
                Log4netHelper.Error(ex);
            }
        }

        private void PlayForm_Load(object sender, EventArgs e)
        {
         
            if (_playerManager == null)
            {
                _playerManager = new PlayerManager(this,this.pictureBox1, _url);
                _playerManager.ContionStatusChange += _playerManager_ContionStatusChange;
                if (_playerManager.is_sdk_init_)
                {
                    _playerManager.Play();
                }
            }
        }

        private void _playerManager_ContionStatusChange(NTSmartPlayerDefine.NT_SP_E_EVENT_ID code)
        {
            var str = "";
            switch (code)
            {
                case NTSmartPlayerDefine.NT_SP_E_EVENT_ID.NT_SP_E_EVENT_ID_CONNECTING:
                    str = "连接中";
                    break;
                case NTSmartPlayerDefine.NT_SP_E_EVENT_ID.NT_SP_E_EVENT_ID_CONNECTED:
                    str = "";
                    break;
                case NTSmartPlayerDefine.NT_SP_E_EVENT_ID.NT_SP_E_EVENT_ID_DISCONNECTED:
                    str = "连接已断开";
                    break;
                case NTSmartPlayerDefine.NT_SP_E_EVENT_ID.NT_SP_E_EVENT_ID_CONNECTION_FAILED:
                    str = "连接失败";
                    break;
            }
            str = string.IsNullOrWhiteSpace(str) ? "同屏中..." : str;
            this.BeginInvoke(new Action(() => { this.Text = str; }));
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            FormBorderStyle = FormBorderStyle == FormBorderStyle.None ? FormBorderStyle.FixedSingle : FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
        }

        public void CloseWin()
        {
            try
            {
                _playerManager?.Close();
            }
            catch (Exception ex)
            {
                Log4netHelper.Error(ex);
            }
            finally
            {
                this.Close();
            }
        }
    }
}
